<template>
  <div class="main-container">
    <div class="left-container">
      <div class="left-container-top" @click="back">
        <svg
          width="12"
          height="23"
          viewBox="0 0 17 28"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M12.816 27.1456C13.4813 27.2521 14.1971 27.2206 14.812 26.9349C16.0417 26.3616 16.4007 25.133 15.6005 24.2357L6.13011 13.6057L15.9192 3.26836C16.7463 2.39584 16.4247 1.15683 15.2131 0.546425C14.0014 -0.0620508 12.2964 0.158828 11.469 1.03327L0.667337 12.4389C0.062737 13.0757 0.0494345 13.951 0.634404 14.6059L11.0845 26.3345C11.4847 26.7841 12.151 27.0391 12.816 27.1456Z"
            fill="#FF5F04"
          />
        </svg>
      </div>
      <div>
        <img style="width: 100%;" :src="product.puductImage" />
      </div>
    </div>
    <div class="right-container">
      <div class="right-container-top">
        {{ this.product.name }}
      </div>
      <div class="right-container-middle-one">
        <div class="right-container-originolPrice">
          {{ this.product.finalPrice }}
        </div>
        <el-input
          class="search"
          style="width: 30%;margin-left:20px;"
          v-model="product.originolPrice"
          maxlength="10"
          @input="handleInput"
          clearable
        ></el-input>
        <el-button @click="submitForm" class="submit">{{
          $t("home.submit")
        }}</el-button>
      </div>
      <div class="right-container-middle-two">
        {{ $t("home.pricingExplanation") }}
      </div>
      <el-card shadow="hover" class="right-container-bottom">
        <div style="display: flex;justify-content: space-between;">
          <span style="white-space: nowrap;">{{ $t("home.salesData") }}</span>
          <div style="display: flex;">
            <div class="filter-btns">
              <div
                class="btn-item"
                :class="btnIndex == b ? 'btn-active' : 'btn-unactive'"
                v-for="(btn, b) in btns"
                :key="b"
                @click="btnClick(btn, b)"
              >
                {{ btn.name }}
              </div>
            </div>
            <div class="daterange">
              <el-date-picker
                v-model="dateTime"
                type="daterange"
                size="small"
                range-separator="-"
                start-placeholder="Start time"
                end-placeholder="End time"
                @change="changeDate"
              >
              </el-date-picker>
            </div>
          </div>
        </div>
        <div
          ref="echartsRef"
          style="width: 100%; height: 240px;margin-top:12%;"
        ></div>
      </el-card>
    </div>
  </div>
</template>
<script>
import * as echarts from "echarts";
import { updateProducts, queryProductCount } from "../../api/productService";
import dayjs from "dayjs";
export default {
  components: {},
  data() {
    return {
      form: {
        name: "",
        region: ""
      },
      dateTime: [],
      //imageUrl: this.$route.query.puductImage, //require("@/assets/img/product.png"),
      product: {
        name: this.$route.query.pruoductTitle,
        originolPrice: this.$route.query.puductPrice,
        finalPrice: this.$route.query.puductPrice,
        productId: this.$route.query.productId,
        variableId: this.$route.query.variableId,
        puductImage: this.$route.query.puductImage
      },
      btns: [
        { name: "LAST 7 DAYS", value: "1", check: false },
        { name: "LAST MONTH", value: "2", check: false },
        { name: "TODAY", value: "3", check: false }
      ],
      btnIndex: -1,
      params: {
        endDate: "",
        startDate: "",
        variableId: this.$route.query.variableId
      },
      salesData: [],
      profitData: [],
      xAxisData: []
    };
  },
  // mounted() {
  //   this.initChart();
  // },
  created() {
    this.getProductCount();
  },
  methods: {
    // 获取当前页的数据信息
    async getProductCount() {
      const res = await queryProductCount(this.params);

      if (res.code === 200) {
        this.salesData = res.data.seriesData.salesData;
        this.profitData = res.data.seriesData.profitData;
        this.xAxisData = res.data.xaxisData;
      } else {
        this.$message.error(res.msg);
      }
      this.initChart();
    },
    back() {
      this.$router.go(-1);
    },
    getProductDataById() {
      // 查询数据
    },
    submitForm() {
      if (
        this.product.originolPrice === "" ||
        this.product.originolPrice === null
      ) {
        this.product.originolPrice = this.product.finalPrice;
        return;
      }
      this.$confirm(this.$t("home.productTip"), "", {
        confirmButtonText: "Change",
        cancelButtonText: "Cancel",
        type: "error",
        center: true,
        roundButton: true,
        cancelButtonClass: "cancel-button-class",
        confirmButtonClass: "confirm-button-class"
      })
        .then(async () => {
          let params = {
            productId: this.product.productId,
            variableId: this.product.variableId,
            price:
              this.product.originolPrice === "" ||
              this.product.originolPrice === null
                ? 0
                : this.product.originolPrice
          };
          let res = await updateProducts(params);
          if (res.code === 200) {
            this.$message.success(this.$t("home.operationSuccess"));
            this.product.finalPrice = this.product.originolPrice;
            this.$route.query.puductPrice = this.product.finalPrice;
          } else {
            this.product.originolPrice = this.product.finalPrice;
            this.$message.error(res.msg);
          }
        })
        .catch(() => {
          this.product.originolPrice = this.product.finalPrice;
        });
    },
    handleInput() {
      // 使用正则表达式过滤输入内容，只保留数字、小数点，且小数点最多一个
      this.product.originolPrice = this.product.originolPrice.replace(
        /[^\d.]/g,
        ""
      );
      // 去除多个小数点
      const dotCount = (this.product.originolPrice.match(/\./g) || []).length;
      if (dotCount > 1) {
        const index = this.product.originolPrice.indexOf(".");
        this.product.originolPrice =
          this.product.originolPrice.slice(0, index + 1) +
          this.product.originolPrice.slice(index + 1).replace(/\./g, "");
      }
      // 限制不能以两个或以上的 0 开头
      if (/^00/.test(this.product.originolPrice)) {
        this.product.originolPrice = this.product.originolPrice.replace(
          /^0+/,
          "0"
        );
      }

      // 限制不能以 . 开头
      if (this.product.originolPrice.startsWith(".")) {
        this.product.originolPrice = "0" + this.product.originolPrice;
      }
    },
    btnClick(item, index) {
      if (this.btnIndex == index) this.btnIndex = -1;
      else this.btnIndex = index;
      if (item.value == "1") {
        // 7天
        this.params.startDate = dayjs()
          .subtract(7, "day")
          .format("YYYY-MM-DD");
        this.params.endDate = dayjs().format("YYYY-MM-DD");
      } else if (item.value == "2") {
        // month
        this.params.startDate = dayjs()
          .date(1)
          .format("YYYY-MM-DD");
        this.params.endDate = dayjs().format("YYYY-MM-DD");
      } else {
        // 今天
        this.params.startDate = dayjs().format("YYYY-MM-DD");
        this.params.endDate = dayjs().format("YYYY-MM-DD");
      }
      if (this.btnIndex == -1) {
        this.params.startDate = "";
        this.params.endDate = "";
      }
      this.dateTime = [];
      this.getProductCount();
    },
    changeDate(date) {
      this.btnIndex = -1;
      if (date) {
        this.params.startDate = date[0];
        this.params.endDate = date[1];
        this.getProductCount();
      } else {
        this.params.startDate = "";
        this.params.endDate = "";
        this.getProductCount();
      }
    },
    initChart() {
      // 基于准备好的dom，初始化echarts实例
      const myChart = echarts.init(this.$refs.echartsRef);
      // 指定图表的配置项和数据
      const option = {
        title: {},
        tooltip: {
          trigger: "axis"
        },
        legend: {
          data: ["Sales Data", "Profit Data"]
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.xAxisData
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            name: "Sales Data",
            type: "line",
            stack: "总量",
            itemStyle: {
              color: "#FBE38E" // 设置 Profit Data 线条颜色为绿色
            },
            data: this.salesData
          },
          {
            name: "Profit Data",
            type: "line",
            stack: "总量",
            itemStyle: {
              color: "#9A89FF" // 设置 Profit Data 线条颜色为绿色
            },
            data: this.profitData
          }
        ]
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    }
  }
};
</script>
<style scoped>
@import "../../assets/css/SalesDataDetail.css";

.right-container-bottom {
  /* 超出部分隐藏 */
  overflow-y: hidden;
  overflow-x: auto;
}
.right-container-bottom::-webkit-scrollbar {
  width: 0;
  height: 0;
}
.filter-btns {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 6px;
  margin-right: 20px;
}

.filter-btns .btn-item {
  color: #666;
  font-size: 13px;
  margin: 0 5px 0 25px;
  padding: 0 10px;
  height: 32px;
  line-height: 32px;
  cursor: pointer;
  border-radius: 10px;
  box-shadow: -2px 3px 10px rgba(0, 0, 0, 0.2);
  white-space: nowrap;
}

.filter-btns .btn-active {
  background: #ffba88;
}

.daterange .el-date-editor {
  width: 240px;
  height: 34px;
  border-radius: 10px;
  box-shadow: -2px 3px 10px rgba(0, 0, 0, 0.2);
}
</style>
